/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.xxhong.xxtv.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.BrandedFragment;
import android.support.v17.leanback.app.BrowseFragment;
import android.support.v17.leanback.app.RowsFragment;
import android.support.v17.leanback.transition.TransitionHelper;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.OnItemViewSelectedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.text.Html;
import android.text.Spannable;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.dangbei.dangbeipaysdknew.DangBeiPayActivity;
import com.xxhong.xxtv.*;
import com.xxhong.xxtv.activity.DetailsActivity;
import com.xxhong.xxtv.activity.MainActivity;
import com.xxhong.xxtv.service.MovieList;
import com.xxhong.xxtv.domain.Poems;
import com.xxhong.xxtv.presenter.PoemDetailPresenter;
import com.xxhong.xxtv.utils.PersistTool;
import com.xxhong.xxtv.utils.XxtvData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/*
 * LeanbackDetailsFragment extends DetailsFragment, a Wrapper fragment for leanback details screens.
 * It shows a detailed view of video and its meta plus related videos.
 */
public class DetailsFragment extends BrandedFragment {
    private Poems poems;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        poems = (Poems) getActivity().getIntent()
                .getSerializableExtra(DetailsActivity.MOVIE);
    }

    TextView mTitle, mSubtitle, mBody;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.poem_details_description, null);
        mTitle = (TextView) view.findViewById(R.id.lb_details_description_title);
        mSubtitle = (TextView) view.findViewById(R.id.lb_details_description_subtitle);
        mBody = (TextView) view.findViewById(R.id.lb_details_description_body);
        RelativeLayout rlBg = (RelativeLayout) view.findViewById(R.id.rl_background);
        mTitle.setText(poems.getTitle());
        mSubtitle.setText(poems.getAuthor());
        setContent("诗文");


        RowsFragment mRowsFragment = (RowsFragment) getChildFragmentManager().findFragmentById(
                R.id.frag_details_rows_dock);
        if (mRowsFragment == null) {
            mRowsFragment = new RowsFragment();
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.frag_details_rows_dock, mRowsFragment).commit();
        }
        ArrayObjectAdapter objectAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        GridItemPresenter mGridPresenter = new GridItemPresenter();
        ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter);
        gridRowAdapter.add("朗读");
        gridRowAdapter.add("诗文");
        gridRowAdapter.add("注释");
        gridRowAdapter.add("译文");
        gridRowAdapter.add("赏析");

        objectAdapter.add(new ListRow(null, gridRowAdapter));
        mRowsFragment.setAdapter(objectAdapter);
        mRowsFragment.setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder,
                                      Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                setContent((String) item);
            }
        });

        return view;
    }

    private void setContent(String type) {
        if ("诗文".equals(type)) {
            String[] split = poems.getContent().split("。");
            String[] split1 = poems.getContent_py().split("。");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
//            sb.append(split1[i]+"\n");
                sb.append(split[i] + "。\n");
            }
            mBody.setText(sb.toString());
        } else if ("注释".equals(type)) {
            String replace = poems.getPoem_desc().replaceAll("<p>", "").replaceAll("</p>", "");
            mBody.setText(replace);
        } else if ("译文".equals(type)) {
            String replace = poems.getPoem_desc2().replaceAll("<p>", "").replaceAll("</p>", "");
            mBody.setText(replace);
        } else if ("赏析".equals(type)) {
            String replace = poems.getPoem_desc3().replaceAll("<p>", "").replaceAll("</p>", "");
            mBody.setText(replace);
        }else if("朗读".equals(type)){
            if(!XxtvData.isReg()){
                startPay();
            }else{
                //播放
                Toast.makeText(getActivity(),"已支付成功",Toast.LENGTH_LONG).show();
            }


        }
    }

    private class GridItemPresenter extends Presenter {
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent) {
            TextView view = new TextView(parent.getContext());
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.setBackgroundColor(getResources().getColor(R.color.default_background));
            view.setTextColor(Color.WHITE);
            view.setGravity(Gravity.CENTER);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, Object item) {
            ((TextView) viewHolder.view).setText((String) item);
        }

        @Override
        public void onUnbindViewHolder(ViewHolder viewHolder) {
        }
    }

    public static void onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            Log.i("xxhong", "上");

        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            Log.i("xxhong", "下");
        }
    }
    public void startPay(){
        Intent intent = new Intent();
        intent.setClass(getActivity(), DangBeiPayActivity.class);
        intent.putExtra("PID","001"); //商品id，最大长度为40个字符，必填
        intent.putExtra("Pname","唐诗语音"); //商品名称，最大长度为60个字符，必填
        intent.putExtra("Pprice","0.01"); //商品价格，必填
                intent.putExtra("Pdesc","一次购买终身受用"); //商品描述，最大长度为60个字符，必填
                        intent.putExtra("Pchannel","10000"); //渠道号，必填
                startActivityForResult(intent, 0);
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("xxhong","onActivityResult");
        if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            int back = bundle.getInt("back");//back为返回值
            if(back==1){
                //支付成功
                XxtvData.reg();
                Toast.makeText(getActivity(),"已支付成功",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getActivity(),"支付失败",Toast.LENGTH_LONG).show();
            }

        }
    }


}
